<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="系统模块" prop="module">
        <el-input v-model="queryParams.module" placeholder="请输入系统模块" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="操作人员" prop="operator">
        <el-input v-model="queryParams.operator" placeholder="请输入操作人员" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="操作地点" prop="location">
        <el-input v-model="queryParams.location" placeholder="请输入操作地点" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="操作类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择操作类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_operate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择操作状态" size="small" clearable>
          <el-option
            v-for="dict in dict.type.sys_operate_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker v-model="dateRange" style="width: 191px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['system:operation-log:list']" type="primary" icon="el-icon-search" size="small"
                   @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button v-hasPermi="['system:operation-log:delete']" type="danger" :disabled="multiple" plain
                   icon="el-icon-delete" size="small" @click="handleDelete">批量删除
        </el-button>
        <el-button v-hasPermi="['system:operation-log:delete']" type="danger" :disabled="!list.length" plain
                   icon="el-icon-delete" size="small" @click="handleClear">清空日志
        </el-button>
        <el-button v-hasPermi="['system:operation-log:export']" type="warning" plain icon="el-icon-download"
                   size="small"
                   @click="handleExport">导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" ref="tables" :data="list" @selection-change="handleSelectionChange"
              :default-sort="{prop: 'operTime', order: 'descending'}" @sort-change="handleSortChange">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column label="系统模块" align="center" prop="module" :show-overflow-tooltip="true"/>
      <el-table-column label="操作类型" align="center" prop="businessType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_operate_type" :value="scope.row.businessType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作人员" align="center" prop="operator" :show-overflow-tooltip="true"/>
      <el-table-column label="操作地址" align="center" prop="ip" :show-overflow-tooltip="true"/>
      <el-table-column label="操作地点" align="center" prop="location" :show-overflow-tooltip="true"/>
      <el-table-column label="操作状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_operate_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column sortable label="操作日期" align="center" prop="operTime" :show-overflow-tooltip="true"/>
      <el-table-column sortable label="操作耗时" align="center" prop="costTime">
        <template slot-scope="scope">
            {{scope.row.costTime}}毫秒
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['system:operation-log:delete']" type="text" icon="el-icon-delete" size="mini"
                     @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
            v-hasPermi="['system:operation-log:get']"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="float: right;margin-top: 20px;" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" background :current-page="queryParams.currentPage"
                   :page-sizes="[5,10,50,100]" :page-size="queryParams.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <!-- 操作日志详细 -->
    <el-dialog title="操作日志详细" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作模块：">{{ form.module }} / {{ typeFormat(form.businessType) }}</el-form-item>
            <el-form-item
              label="登录信息："
            >{{ form.operator }} / {{ form.ip }} / {{ form.location }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求地址：">{{ form.reqUrl }}</el-form-item>
            <el-form-item label="请求方式：">{{ form.reqMethod }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作方法：">{{ form.method }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求参数：">{{ form.reqParam }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="返回参数：">{{ form.respParam }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作状态：">
              <div v-if="form.status === 0">正常</div>
              <div v-else-if="form.status === 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消耗时间：">{{ form.costTime }}毫秒</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="操作时间：">{{ form.operTime }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listOperationLog, delOperationLog, clearOperationLog} from "@/api/system/operation-log";

export default {
  name: "OperationLog",
  dicts: ['sys_operate_status', 'sys_operate_type'],
  data() {
    return {
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表格数据
      list: [],
      // 日期范围
      dateRange: [],
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        module: '',
        operator: '',
        businessType: '',
        status: '',
        location: ''
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleCurrentChange(val) {
      this.queryParams.currentPage = val;
      this.getList()
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList()
    },
    /** 查询登录日志 */
    getList() {
      this.loading = true
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.beginTime = undefined
        this.queryParams.endTime = undefined
      }
      listOperationLog(this.queryParams).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.loading = false
      });
    },
    /** 排序触发事件 */
    handleSortChange(column) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.asc = column.order === 'ascending';
      this.getList();
    },
    // 操作日志类型字典翻译
    typeFormat(businessType) {
      if (businessType === undefined) {
        return "";
      }
      let datas = this.dict.type.sys_operate_type
      let actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].value == ('' + businessType)) {
          actions.push(datas[key].label);
          return true;
        }
      })
      if (actions.length === 0) {
        actions.push(businessType);
      }
      return actions.join('');
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {}
      this.dateRange = []
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = row.id || this.ids
      this.$confirm(`此操作删除id为【${ids}】的日志, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delOperationLog(ids).then(res => {
          this.getList();
          this.$message.success("删除成功");
        })
      }).catch(() => {
      });
    },
    handleClear() {
      this.$confirm(`此操作将删除所有日志, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clearOperationLog().then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/operation-log/export', {
        ...this.queryParams
      }, '操作日志表.xlsx')
    }
  }
};
</script>
